package com.zerocarbon.framework.db.mybatis.typehandler;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.Alias;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Alias("urlPrefix")
public class UrlPrefixTypeHandler<T extends Object> extends BaseTypeHandler<T> {

    private String urlPrefix;

    public UrlPrefixTypeHandler() {}

    public UrlPrefixTypeHandler(String urlPrefix) {
        this.urlPrefix = urlPrefix;
    }

    // java -> db
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) {
            ps.setString(i, null);
        } else {
            ps.setString(i, parameter.toString().replace(urlPrefix, ""));
        }
    }

    // db -> java
    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return (T)addUrlPrefix(rs.getString(columnName));
    }

    // db -> java
    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return (T)addUrlPrefix(rs.getString(columnIndex));
    }

    // db -> java
    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return (T)addUrlPrefix(cs.getString(columnIndex));
    }

    public String addUrlPrefix(String columnName) {
        if (StringUtils.isNotBlank(columnName)) {
            columnName = urlPrefix + columnName;
        }
        return columnName;
    }

}
